﻿using B.S.Traceability.Domain;
using B.S.Traceability.ErrorCode;
using B.S.Traceability.Infra.Interfaces;
using B.S.Traceability.WebAPI.Write.Commands;
using MediatR;

namespace B.S.Traceability.WebAPI.Write.CommandHandlers
{
    public class DelShopsCommandHandler : IRequestHandler<DelShopsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Shops> _baseRepository;

        public DelShopsCommandHandler(IBaseRepository<Shops> baseRepository)
        {
            _baseRepository = baseRepository;
        }

        public async Task<APIResult<int>> Handle(DelShopsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.Success;
            result.Msg = "删除成功";

            // 解析 Ids 字符串为整数数组
            var ids = request.Ids.Split(',')
                                 .Select(int.Parse)
                                 .ToArray();

            // 根据 Ids 查询对应的 Commodity 记录
            var commoditiesToDelete = _baseRepository.GetAll()
                                                    .Where(c => ids.Contains(c.ShopId))
                                                    .ToList();

            if (commoditiesToDelete.Count > 0)
            {
                // 批量删除记录
                foreach (var commodity in commoditiesToDelete)
                {
                    commodity.isDel = true;
                    _baseRepository.Update(commodity);
                }

                result.Code = APIEnum.Success;
                result.Msg = "删除成功";
                result.Data = commoditiesToDelete.Count;
            }
            else
            {
                result.Code = APIEnum.Failed;
                result.Msg = "删除失败";
                result.Data = 0;
            }

            return await Task.FromResult(result);
        }
    }
}
